package controllers;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;
import models.LinkModel;

import data.CategoryData;
import data.LinkData;
import debug.LinkDebug;

public class ViewCategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		String path = ((HttpServletRequest) request).getRequestURI();
		long categoryId = 0;
		try {
			categoryId = Long.parseLong(URLDecoder.decode(path.toLowerCase().replaceAll("/view-category/", ""),"UTF-8"));
		} catch (Exception e) {
			response.sendRedirect("/message?txt=page-not-found");
			return;
		}
		
		CategoryData cData = new CategoryData();
		LinkData linkData = new LinkData();
		
		CategoryModel category = cData.getCategory(categoryId);
		
		ArrayList<CategoryModel> categories = cData.listChildren(categoryId);
		ArrayList<LinkModel> links = linkData.listByCategory(categoryId);
		ArrayList<CategoryModel> parents = cData.listParents(categoryId);
		
		request.setAttribute("categories", categories);
		request.setAttribute("category", category);
		request.setAttribute("parents", parents);
		request.setAttribute("links", links);
		
		try {
			request.getRequestDispatcher("/pages/view_category.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
